﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MongoDbWebClient.Common;
using MongoDB.Driver;

namespace MongoDbWebClient.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult ConnectToServer(string host, string port,string user,string password)
        {
            string res = string.Empty;
            try
            {
                if (string.IsNullOrEmpty(user) && string.IsNullOrEmpty(password))
                {
                    if (string.IsNullOrEmpty(port))
                    {
                        res = ServersPool.AddServerToWatch(ServersPool.GetConnectionString(host));
                    }
                    else
                    {
                        res = ServersPool.AddServerToWatch(ServersPool.GetConnectionString(host, port));
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(port))
                    {
                        res = ServersPool.AddServerToWatch(ServersPool.GetConnectionString(user, password,host));
                    }
                    else
                    {
                        res = ServersPool.AddServerToWatch(ServersPool.GetConnectionString(user, password,host, port));
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "Error", Message = ex.Message });
            }

            Response.SetCookie(new HttpCookie(host, res));
            MongoServer server = ServersPool.GetServer(res);

            var dbs = server.GetDatabaseNames();
            string dbsJson;
            if (dbs.Count() > 0)
            {
                dbsJson = string.Format("['{0}']", string.Join("','", dbs));
            }
            else
            {
                dbsJson = "[]";
            }
            return Json(new { Result = "OK", Server = host, Key = res, 
                      Dbs = dbs  
            });
        }

    }
}
